package com.loiane.util;

import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;
import com.loiane.model.Account;

@Component
public class AccountUtil {

	public List<Account> getAccountsFromRequest(Object data) {
		List<Account> list;

		// it is an array - have to cast to array object
		if (data.toString().indexOf('[') > -1) {

			list = getListAccountsFromJSON(data);

		} else { // it is only one object - cast to object/bean

			Account account = getContactFromJSON(data);

			list = new ArrayList<Account>();
			list.add(account);
		}

		return list;
	}

	@SuppressWarnings("unchecked")
	private List<Account> getListAccountsFromJSON(Object data) {
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<Account> newAccounts = (List<Account>) JSONArray.toCollection(
				jsonArray, Account.class);
		return newAccounts;
	}

	private Account getContactFromJSON(Object data) {
		JSONObject jsonObject = JSONObject.fromObject(data);
		Account newAccount = (Account) JSONObject.toBean(jsonObject,
				Account.class);
		return newAccount;
	}

	@SuppressWarnings("unchecked")
	public List<Integer> getListIdFromJSON(Object data) {
		JSONArray jsonArray = JSONArray.fromObject(data);
		List<Integer> idAccounts = (List<Integer>) JSONArray.toCollection(
				jsonArray, Integer.class);
		return idAccounts;
	}
}
